// 上传
import { CSSProperties, useRef, useState, } from 'react';
import { message, } from 'antd';
import oss from 'ali-oss';
import moment from 'moment';


function RealUpload(props: {
    dispatch?: any;
    businessName: string;  // 业务串
    onUploadDone: (p: any) => void;  // 上传完成事件
    size?: number;  // 大小（M）
    accept?: string;  // 允许上传文件类型
    style?: CSSProperties
}) {
    const { style = {}, dispatch, businessName, size = 20, accept = 'image/jpeg, image/png', onUploadDone, } = props;
    const [ossToken, setOssToken] = useState<any>({});  // oss直传参数

    const uploadInput = useRef<any>(null);  // 上传input对象

    // 上传文件change事件
    const handleChange = (e: any) => {
        e.stopPropagation();
        const file = e.target.files[0];
        uploadInput.current.value = '';
        // 格式验证 目前只有上传图片accept已写死(.jpeg .jpg .png) 暂时不考虑其他类型

        // 大小验证
        if (file.size / 1024 / 1024 > size) {
            message.error(`请上传大小不超过${size}M的图片`);
            return
        }
        // 上传oss
        uploadOSS(file);
    }

    // 上传oss
    const uploadOSS = (file: any) => {
        if (Object.keys(ossToken).length === 0) {
            // 第一次
            getOSSParams().then((res: any) => {
                if (res !== null) {
                    setOssToken(res);
                    // 上传
                    upload(res, file);
                }
            })
        } else {
            // 上传
            upload(ossToken, file);
        }
    }

    // 上传
    const upload = (ossParams: any, file: any) => {
        const url = uploadPath(file);
        new oss(ossParams).multipartUpload(url, file, {}).then((data) => {
            const { name } = data;
            onUploadDone(name);
        }).catch((error) => {
            
        });
    }

    // 初始化oss参数
    const getOSSParams = () => {
        return new Promise ((res, rej) => {
            dispatch({
                type: 'aliyunOss/getTemOssAuth',
                payload: {},
                callback: (e: { code: number, data: any }) => {
                    const { code, data } = e;
                    if (code === 1) {
                        const { accessKeyId, accessKeySecret, endPoint: endpoint, bucket, region, securityToken: stsToken } = data;
                        res({ accessKeyId, accessKeySecret, endpoint, bucket, region, stsToken });
                    } else {
                        rej(null)
                    }
                },
            });
        });
        
    }

    // oss保存路径
    const uploadPath = (file: any) => {
        const { tenantId } = JSON.parse(sessionStorage.getItem('mlxcMaxOrg') || '{"tenantId": "test001"}');
        const path = `/business/tenant_${tenantId}/${businessName}`
        const now = Date.now();
        const fileTypeArr = file.name ? file.name.split('.') : [];
        const fileType = fileTypeArr.length > 0 ? fileTypeArr[fileTypeArr.length - 1] : '';
        const url = fileType
            ? `${path}/${moment().format('YYYYMMDD')}/${now}.${fileType}`
            : `${path}/${moment().format('YYYYMMDD')}/${now}.${file.type.split('/')[1]}`;
        return url;
    }

    return (
        <input ref={uploadInput} type='file' style={style} accept={accept} onChange={handleChange} />
    );
}

export default RealUpload;
